package com.lkm.app_ui.ui;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.MBaseFragment;
import com.lkm.app_ui.R;
import com.lkm.app_ui.RouterUINavigation;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.help.AppUIHelp;
import com.lkm.app_ui.m.fun.OnKeyNumberEvent;
import com.lkm.app_ui.m.goods.BarcodeResultBO;
import com.lkm.frame.otto.LinkBusCycleWrapper;
import com.lkm.frame.otto.Observer;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.util.CycleHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.market2_0.help.SteelardHelp;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;
import com.lkm.market2_0.m.steelyarddata.SteelyardDataModule;
import com.lkm.market2_0.m.steelyardserver.OnSteelyardKeyEvent;
import com.lkm.market2_0.m.steelyardserver.to.WeightChangeInfo;
import com.lkm.market2_0.m.steelyardserver.event.OnWeightInfoChangeEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;



public class CountNumFragment extends MBaseFragment {


    public static CountNumFragment getInstance(boolean isBarcodeResult) {
        CountNumFragment f = new CountNumFragment();
        Bundle data = new Bundle();
        data.putBoolean("isBarcodeResult", isBarcodeResult);

        f.setArguments(data);


        return f;
    }

    public static CountNumFragment instance;


    public CountNumFragment() {
        instance = this;
    }

    @Override
    protected int configLayoutResID() {
        return R.layout.fragment_countnum;
    }

    @Override
    protected boolean configIsLockKey() {
        return true;
    }

    private float weight1;

    private float unitPrice1 = -1;
    private String name1 = "";



    private WeightChangeInfo weightChangeInfo;

    TextView tv_name1, tv_weight1, tv_price1, tv_money;


    private boolean isBarcodeResult = false;


    private BarcodeResultBO barcodeResultBO;


    private boolean isChangePrice = false;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        interceptedKeyAndNumberEvent();
        reOnWeightInfoChangeEvent();

        isBarcodeResult = getArguments().getBoolean("isBarcodeResult", false);

        tv_name1 = ((TextView) findViewById(R.id.tv_name1));//.setText(weightChangeInfo.getName());
        tv_weight1 = ((TextView) findViewById(R.id.tv_weight1));//.setText(NumberHelp.formatMoney(weightChangeInfo.getWeight(), 3, "--"));
        tv_price1 = ((TextView) findViewById(R.id.tv_price1));//.setText(SteelardHelp.formatMoney(weightChangeInfo.getUnitPrice()));
        tv_money = ((TextView) findViewById(R.id.tv_money));
        tv_weight1.setText("1.0");


        ((TextView) findViewById(R.id.tv_tips)).setText("数量/单价输入：'单价输入'按钮\n\n确定：'累计'按钮\n\n取消：'功能选择'按钮");

        weight1 = 1.0f;
        if (isBarcodeResult) {
            ((TextView) findViewById(R.id.tv_tips)).append("\n\n称重切换：'商品切换'按钮");

        }
        onInputType();

        if (isBarcodeResult) {
            barcodeResultBO = RunTimeData.barcodeResultBO;
            if(!onBarcodeResultBO()){

                AppUIHelp.tryShowTipsLong("无对应的商品。");
                RouterUINavigation.getInstance().dismiss(this);
            }
        }

    }
    private void onInputType(){

        if(isChangePrice){
            tv_weight1.setBackgroundResource(0);
            AppUIHelp.inputUI(tv_price1);
            ((TextView)findViewById(R.id.tv_tips_weight1)).setText("(件)");
            ((TextView)findViewById(R.id.tv_tips_price1)).setText("(元/件) 请输入单价");
        }else {
            AppUIHelp.inputUI(tv_weight1);
            ((TextView)findViewById(R.id.tv_tips_weight1)).setText("(件) 请输入件数");
            ((TextView)findViewById(R.id.tv_tips_price1)).setText("(元/件)");
            tv_price1.setBackgroundResource(0);
        }
    }

    private boolean onBarcodeResultBO() {
        if (barcodeResultBO == null) return false;

        unitPrice1 = StringHelp.toFloat(barcodeResultBO.price, unitPrice1);
        name1 = barcodeResultBO.goodsEntity == null ? "" : barcodeResultBO.goodsEntity.name;

        return barcodeResultBO.goodsEntity!=null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();


        if (instance == this)
            instance = null;

    }


    private void reOnWeightInfoChangeEvent() {
        LinkBusCycleWrapper.register(new Observer<OnWeightInfoChangeEvent>() {
            @Override
            public Class<OnWeightInfoChangeEvent> getBusEventClass() {
                return OnWeightInfoChangeEvent.class;
            }

            @Override
            public void onReceiver(OnWeightInfoChangeEvent data, Runnable nextRun) {
                try {
                    String steelyardMac = data.getSteelyardMac();


                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            weightChangeInfo = data.getWeightChangeInfo();
                            if (isExit()) return;
                            if(unitPrice1==-1)
                                unitPrice1 = weightChangeInfo.getUnitPrice();
                            upWeightInfo(weightChangeInfo);

                        }
                    });


                } finally {
                    nextRun.run();
                }
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }


    private void upWeightInfo(WeightChangeInfo weightChangeInfo) {
        weightChangeInfo.setUnitType(2);


        weightChangeInfo.setWeight(weight1);

        weightChangeInfo.setUnitPrice(unitPrice1);
        weightChangeInfo.setTotalPrice(SteelardHelp.calPrice(weightChangeInfo.getUnitPrice(), weightChangeInfo.getWeight()));


        if (!StringHelp.isEmpty(name1)) {
            weightChangeInfo.setName(name1);
        }

        tv_name1.setText(weightChangeInfo.getName());
        tv_price1.setText(SteelardHelp.formatMoney(weightChangeInfo.getUnitPrice()));
        tv_money.setText(SteelardHelp.formatMoney(weightChangeInfo.getTotalPrice()));
        tv_weight1.setText("" + weightChangeInfo.getWeight());
    }


    private void interceptedKeyAndNumberEvent() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnSteelyardKeyEvent>() {
            @Override
            public Class<OnSteelyardKeyEvent> getBusEventClass() {
                return OnSteelyardKeyEvent.class;
            }

            @Override
            public void onReceiver(OnSteelyardKeyEvent data) {
                if (!data.isIntercepted()) {
                    data.setIntercepted(true);
                    if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_FUN) {
                        RouterUINavigation.getInstance().dismiss(CountNumFragment.this);
                    } else if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_LEIJI) {

                        if (weightChangeInfo == null) return;

                        SteelyardDataModule steelyardDataModule = (SteelyardDataModule) AppConst.getModuleManager().peekModule(SteelyardDataModule.class);
                        if (steelyardDataModule != null) {
                            upWeightInfo(weightChangeInfo);

                            OrderEntity.GoodEntity goodEntity = OrderEntity.GoodEntity.toGoodEntity(RunTimeData.steelyardInfo, weightChangeInfo, new OrderEntity.GoodEntityEx());
                            if (barcodeResultBO != null && barcodeResultBO.goodsEntity != null) {
//                                goodEntity.addExtData("goods", barcodeResultBO.goodsEntity);
                                goodEntity.goodCode = barcodeResultBO.goodsEntity.code;
                                goodEntity.goodId = barcodeResultBO.goodsEntity.id;
                            }

                            steelyardDataModule.subtotal(RunTimeData.LoaclSteelyardMac, goodEntity );
                        }
                        RouterUINavigation.getInstance().dismiss(CountNumFragment.this);

                    } else if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_INPUT_PRICE) {


                        isChangePrice = !isChangePrice;
                        isOnce = false;
                        onInputType();

                    } else if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_GOODQIEH) {
                        if (isBarcodeResult) {

                            RouterUINavigation.getInstance().dismiss(CountNumFragment.this);
                            RouterUINavigation.getInstance().showBarcodeResult();
                        }
                    }
                }

            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);



        LinkBusCycleWrapper.register(new ObserverAutoNext<OnKeyNumberEvent>() {
            @Override
            public Class<OnKeyNumberEvent> getBusEventClass() {
                return OnKeyNumberEvent.class;
            }



            @Override
            public void onReceiver(OnKeyNumberEvent data) {
                if (!data.isIntercepted()) {
                    data.setIntercepted(true);
                    if (!isOnce && data.isFinally()) {

                        isOnce = true;
                        return;
                    }
                    isOnce = true;

                    if(isChangePrice){
                        unitPrice1 = data.getNumber();
                    }else{
                        weight1 = data.getNumber();
                    }

                    if (weightChangeInfo != null) {
                        upWeightInfo(weightChangeInfo);
                    }

//                    tv_weight1.setText(NumberHelp.formatMoney(weightChangeInfo.getWeight(), 3, "--"));

                }
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }
    boolean isOnce = false;

}
